<!--
  - Copyright (c) 2019.  武汉中科图灵科技有限公司
  - Date :  2019/1/5
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.6.2
  -->

<template>
	<el-dialog
        width="70%"
        :visible.sync="Show"
        :show-close="false"
        top="5vh"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        append-to-body style="" custom-class="innerdialog">
        <div slot="title" class="dialog-header">
          <span class="mark-map-title">{{maptitle}}</span>
          <div class="mark-button">
		          <el-button type="primary" @click="innercreate()" size="mini">保 存</el-button>
		          <el-button @click="innercancel()" type="text" size="mini">取 消</el-button>
          </div>
        </div>
          <div class="mapwrap" v-if="Show">
          	<el-autocomplete
              v-model="searchText"
              :fetch-suggestions="onSearchResult"
              :trigger-on-focus="false"
              placeholder="请搜索或选择地点"
              @select="handleSelect"
              popper-class="dailog-addressbox-list"
              suffix-icon="el-icon-search"
              class="search-box"
              clearable
            >
              <template slot-scope="{ item }">
                <span class="name">{{ item.name }}</span>
                <span class="addr">{{ item.district }}</span>
              </template>
            </el-autocomplete>
	          <el-amap vid="amapDemo" :zoom="zoom" :center="mapCenter" :plugin="plugin" :events="mapevents" class="amap-demo">
	            <el-amap-marker
	            :position="markers.position"
	            :title="'经度：'+markers.position[0]+'纬度：'+markers.position[1]"
	            :events="markers.events"
	            :visible="markers.visible">
	            <div :style="slotStyle">
	            	<i class="el-icon-location"></i>
	          	</div>
	            </el-amap-marker>
	            <el-amap-info-window :position="mwindows.position" :visible.sync="mapmarkvisible" :events="markevents" :content="mwindows.content"></el-amap-info-window>
        	</el-amap>
          </div>
      </el-dialog>
</template>
<script>
	import { AMapManager} from "vue-amap";
  	let amapManager = new AMapManager();
	export default{
    props: {
      Show: {
        required: true,
        default: false
      },
      gis: {
        type: String,
        default: "114.425351,30.50364"
      },
      maptitle: {
        type: String,
        default: ""
      }
    },
		data(){
			let self=this;
			return{
				innerVisible:false,
		        marktext:"",
		        searchText:"",
		        zoom: 14,
		        amapManager,
		        slotStyle: {
		            padding: '2px 8px',
		            fontSize:"35px",
		            color: '#ff7100',
		          },
		        mapmarkvisible:true,
		        markers:
		            {
		              position: [121.5273285, 31.21515044],
		              events: {
		                click: () => {
		                	self.mapmarkvisible = true;
		                },
		                dragend: (e) => {
		                },
		                mouseover:()=>{
		                }
		              },
		              visible: true,
		            },
	        	mapevents:{
	              init: o => {
                o.setMapStyle('amap://styles/117f36d1e643cfd46d21660d866df29e');
	              AMapUI.loadUI(["control/BasicControl"], function(BasicControl) {
	                //缩放控件
	                o.addControl(
	                  new BasicControl.Zoom({
	                    position: "rb" //left top，左上角
	                  })
	                );
	              });
	            },
	            zoomend: () => {
	              let zoomedLevel = document.querySelector(".amap-ui-control-zoom-num")
	               .innerText;
	              self.zoom = parseInt(zoomedLevel);
	            },
	            click(e) {
	                let { lng, lat } = e.lnglat;
	                self.lng = lng;
	                self.lat = lat;

	                // 这里通过高德 SDK 完成。
	                let geocoder = new AMap.Geocoder({
	                  radius: 1000,
	                  extensions: "all"
	                });
	                geocoder.getAddress([lng ,lat], function(status, result) {
	                  if (status === 'complete' && result.info === 'OK') {
	                    self.markers.position=self.mapCenter= [self.lng, self.lat];
	                    self.mwindows.position=	[self.markers.position[0]- 0.0002,self.markers.position[1]+ 0.0028];
	                    if (result && result.regeocode) {
	                      self.address =result.regeocode.formattedAddress;
	                      self.mwindows.content="<span style='color:#999999'>"
	                      	+result.regeocode.formattedAddress;
	                      self.$nextTick();
	                    }
	                  }
	                });
	              }
	            },
	            mwindows: {
	              position: [116.602489, 40.080734],
	              content: ""
	            },
	            markevents:{
			          close() {
			                 self.mapmarkvisible = false
			                }
			      },
		        mapCenter:[116.602489, 40.080734],
		        plugin: [
		            {
		              pName: "Geolocation",
		              events: {
		                init(o) {
		                  // o 是高德地图定位插件实例
		                  o.getCurrentPosition((status, result) => {
				                    if (result && result.position) {
				                      self.deflng = result.position.lng;
				                      self.deflat = result.position.lat;
				                      self.markers.position= [self.deflng, self.deflat];
							            self.mwindows.position=	[self.markers.position[0]- 0.0002,self.markers.position[1]+ 0.0028];
							            self.mwindows.content="当前位置：<span style='color:#999999'>"
							                      	+result.formattedAddress;
				                    }
		                  });
		                }
		              }
		            },
		            {
		              pName: "Scale",
		              events: {}
		            }
		        ],
			}
		},
		methods:{
		  innercreate(){
	          //this.areaForm.gis=this.markers[0].position[0]+","+this.markers[0].position[1];
	          let gis=this.markers.position[0]+","+this.markers.position[1];
	          this.$emit("getMark",gis)
	      },
	      innercancel(){
	      	  this.markers.position=[0,0];
			  this.mwindows.position=[0,0];
	          this.$emit("update:Show",false)
	      },
	      onSearchResult(pois,cb) {
		       let self = this;
		       let searchkey = this.searchText;
		       AMap.plugin(['AMap.Autocomplete'], function() {
		         var autoOptions = {
		            city: '', // 城市，默认全国
		          }
		         var autoComplete = new AMap.Autocomplete(autoOptions)
		         autoComplete.search(searchkey, function(status, result) {
		            // 搜索成功时，result即是对应的匹配数据
		            if(result){
		              let results = result.tips;
		              if(results){
		                  cb(results);
		              } else {
		                //搜索无结果
                      cb("")
                  }
		            }
		          })
		       })
		    },
		    handleSelect(item){
		        this.searchText = item.name;
		        let self=this;
		    	if (item.location=="") {
		    		let placemap=new AMap.Geocoder({
	                  radius: 1000,
	                  extensions: "all"
	                  });
	            	placemap.getLocation(this.searchText,function(status, result) {
					    if (status === 'complete' && result.info === 'OK') {
					    	self.setSearchPos(result.geocodes[0].location)
					    }
				  	})
		    	}else{
		    		self.setSearchPos(item.location)
		    	}
		    },
		    setSearchPos(posi){
		        this.mapCenter=this.markers.position= [posi.lng, posi.lat];
	            this.mwindows.position=	[this.markers.position[0]- 0.0002,this.markers.position[1]+ 0.0028];
	            this.mwindows.content="<span style='color:#999999'>"
	                      	+this.searchText;
		    },
	        firstPlace(pos){
				let self=this;
				let plceposi=[parseFloat(pos.split(",")[0]),parseFloat(pos.split(",")[1])];
				let placename;
				let placemap=new AMap.Geocoder({
                  radius: 1000,
                  extensions: "all"
                  });
			      placemap.getAddress(pos.split(","),function(status, result){
			      	if (status === 'complete' && result.info === 'OK') {
			      			if (result && result.regeocode) {
								self.mapCenter=plceposi;
								self.markers.position=plceposi;
				                self.mwindows.position=	[parseFloat(self.markers.position[0])- 0.0002,parseFloat(self.markers.position[1])+ 0.0028];
				                self.mwindows.content="<span style='color:#999999'>"
		                      	+result.regeocode.formattedAddress;
				              	self.mapmarkvisible=true;
			      			}
			      	}
			      });
			}
		},
		watch:{
			Show:function(val){
				if (val) {
					if (this.gis!="") {
							this.plugin=[];
							this.$nextTick(function(){
								this.firstPlace(this.gis)
							})
					}
				}
			}
		}
	}
</script>
<style lang="scss">
  .dialog-header {
    padding: 16px 10px 26px;
    display: flex;
    justify-content: space-between;
  }
	.mapwrap .amap-info-sharp{
		height:0 !important;
	}
	.mark-map-title{
		font-size: 24px;
		width:70%;
    color: #50E3C2;
	}
	.mapwrap{
		width: 100%;
		height: 740px;
	}
	.innerdialog .el-dialog__body{
		padding: 0;
	}
	.innerdialog{
		border-radius: 10px;
	}
	.search-box{
    width: 300px;
		position:absolute !important;
		margin-left:50%;
		transform:translateX(-50%);
		margin-top:10px;
		z-index:5;
	}
	.innerdialog {
	      .mark-button{
			text-align:left;
			display:inline-block;
	        width: 170px;
	        .el-button{
				float:left;
	        }
	      }
	}
	// 搜索结果列表
.dailog-addressbox-list{
      li{
        .addr{
          font-size: 12px;
          color: #999;
        }
      }
}
</style>
